# _*_ coding: utf-8 _*_
"""
@ 时间    ：2024/10/22 20:12
@ 作者    ：旺财
@ 文件    ：01 员工离职预测模型.py
@ 说明    ：员工离职预测模型
"""

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, roc_curve, roc_auc_score

# 1.读取数据
df = pd.read_excel('员工离职预测模型.xlsx')
print(df.head())

# 2.提取特征变量与目标变量
df['工资'] = df['工资'].map({'低': 0, '中': 1, '高': 2}).astype(int)
x = df.drop(columns='离职')
y = df['离职']
print(x)

# 3.划分训练集和测试集数据,其中test_size=0.2
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=11)

# 4.建立决策树模型（使用默认参数）
mode = DecisionTreeClassifier(max_depth=3)
mode.fit(x_train, y_train)

# 5.预测结果,并通过DataFrame进行展示前5行数据
df_score = pd.DataFrame()
y_pre = mode.predict(x_test)
df_score['预测结果'] = list(y_pre)
df_score['实际结果'] = list(y_test)
print(df_score.head(5))

# 6.预测概率，并通过DataFrame进行展示前5行数据；
y_p = mode.predict_proba(x_test)
df_p = pd.DataFrame(y_p, columns=['不离职概率', '离职概率'])
print(df_p.head(5))

# 7.查看模型预测准确度
# 评估方式1
acc_score = accuracy_score(y_pre, y_test)
print(acc_score)

# 评估方式2
md_score = mode.score(x_test, y_test)
print(md_score)

# 8.计算模型AUC值；
auc_score = roc_auc_score(y_pre, y_test)
print(auc_score)

# 9.查看特征重要性；
df_importance = pd.DataFrame()
df_importance['特征名称'] = x.columns
df_importance['重要性'] = mode.feature_importances_
print(df_importance.sort_values(by='重要性', ascending=False))

# 10.绘制模型ROC曲线
y_pre_proba = mode.predict_proba(x_test)
fpr, tpr, _ = roc_curve(y_test, y_pre_proba[:, 1])
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.plot(fpr, tpr)
plt.title('ROC曲线')
plt.xlabel('假报率-FPR')
plt.ylabel('命中率-TPR')
plt.show()


